import { Plugin, PluginContext, PluginCommand, PluginSetting } from '../PluginManager'

export class WordCountPlugin implements Plugin {
  id = 'word-count'
  name = 'Word Count'
  version = '1.0.0'
  description = 'Shows word count and reading time statistics'
  author = 'IntelliMark Team'
  enabled = false

  private context: PluginContext | null = null
  private updateInterval: NodeJS.Timeout | null = null

  settings: PluginSetting[] = [
    {
      key: 'updateInterval',
      title: 'Update Interval (seconds)',
      description: 'How often to update the word count',
      type: 'number',
      default: 5
    },
    {
      key: 'showReadingTime',
      title: 'Show Reading Time',
      description: 'Display estimated reading time',
      type: 'boolean',
      default: true
    }
  ]

  activate(context: PluginContext): void {
    this.context = context

    // Register commands
    context.registerCommand({
      id: 'word-count.show-stats',
      title: 'Show Word Count Stats',
      description: 'Display detailed word count statistics',
      handler: () => this.showWordCountStats()
    })

    // Start periodic updates
    this.startPeriodicUpdate()

    // Show initial notification
    context.showNotification('Word Count plugin activated', 'success')
  }

  deactivate(): void {
    // Stop periodic updates
    this.stopPeriodicUpdate()
    this.context = null
  }

  private startPeriodicUpdate(): void {
    if (!this.context) return

    const settings = this.getSettings()
    const interval = settings.updateInterval * 1000

    this.updateInterval = setInterval(() => {
      this.updateWordCount()
    }, interval)
  }

  private stopPeriodicUpdate(): void {
    if (this.updateInterval) {
      clearInterval(this.updateInterval)
      this.updateInterval = null
    }
  }

  private updateWordCount(): void {
    if (!this.context) return

    const editor = this.context.editor
    const content = editor.getContent?.() || ''
    const stats = this.calculateStats(content)

    // Update status bar or display stats somewhere
    this.displayStats(stats)
  }

  private calculateStats(content: string) {
    const words = content.split(/\s+/).filter(word => word.length > 0).length
    const characters = content.length
    const charactersNoSpaces = content.replace(/\s/g, '').length
    const paragraphs = content.split(/\n\n+/).filter(p => p.trim().length > 0).length
    const lines = content.split('\n').length

    // Reading time calculation (average 200 words per minute)
    const readingTimeMinutes = Math.ceil(words / 200)

    return {
      words,
      characters,
      charactersNoSpaces,
      paragraphs,
      lines,
      readingTimeMinutes
    }
  }

  private displayStats(stats: any): void {
    if (!this.context) return

    const settings = this.getSettings()
    let message = `Words: ${stats.words} | Characters: ${stats.characters}`

    if (settings.showReadingTime) {
      message += ` | Reading time: ${stats.readingTimeMinutes} min`
    }

    // You could update a status bar component here
    console.log('Word Count:', message)
  }

  private showWordCountStats(): void {
    if (!this.context) return

    const editor = this.context.editor
    const content = editor.getContent?.() || ''
    const stats = this.calculateStats(content)

    const message = `
Document Statistics:
• Words: ${stats.words}
• Characters: ${stats.characters}
• Characters (no spaces): ${stats.charactersNoSpaces}
• Paragraphs: ${stats.paragraphs}
• Lines: ${stats.lines}
• Reading time: ${stats.readingTimeMinutes} minutes
    `.trim()

    // Show in a modal or dialog
    alert(message)
  }

  private getSettings(): { updateInterval: number; showReadingTime: boolean } {
    if (!this.context) return { updateInterval: 5, showReadingTime: true }

    const defaultSettings = {
      updateInterval: 5,
      showReadingTime: true
    }

    // In a real implementation, you would load these from the plugin manager
    return defaultSettings
  }
}

export default WordCountPlugin